﻿package util.wcl
{
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.AdvancedDataGrid;
	import mx.controls.CheckBox;
	import mx.controls.advancedDataGridClasses.AdvancedDataGridListData;
	import mx.controls.listClasses.BaseListData;
	import mx.core.mx_internal;
	
	use namespace mx_internal;
	
	public class CheckBoxRenderer  extends CheckBox
	{
		public static var _headerFlag : Boolean = false;
		
		private var _data:Object;
		
		public function CheckBoxRenderer()
		{
			super();
			this.addEventListener(MouseEvent.CLICK , mouseClickHandler);
		}
		
		
		private function mouseClickHandler(event : Event) : void
		{
			if(AdvancedDataGrid(owner).dataProvider is ArrayCollection) {
				var dgData : ArrayCollection = AdvancedDataGrid(owner).dataProvider as ArrayCollection ;
				
				if(_listData != null && _listData.rowIndex != 0) {
					_headerFlag = selected;
					
					for(var i : int = 0 ; i < dgData.length ; i++) {
						dgData[i][_listData.dataField] = _headerFlag;
					}
				}else{
					dgData[_listData.rowIndex-1][_listData.dataField] = selected;
				}
				AdvancedDataGrid(owner).invalidateList();
			}
		}
		
		private var _listData:AdvancedDataGridListData;
		
		override public function get listData():BaseListData
		{
		  	return _listData;
		}
		
		override public function set listData(value:BaseListData):void
		{
			_listData = AdvancedDataGridListData(value);
		}
		
		override public function set data(value:Object):void
		{
			var advanData:ArrayCollection = AdvancedDataGrid(owner).dataProvider as ArrayCollection ;
			var selectedIdx:int;
			
			if(value == null) {
				return;
			}
			if(_listData.rowIndex != 0 && _listData.rowIndex != -1) {
				_data = value[_listData.dataField];
				selected = _data;
			}else{
				selected = _headerFlag;
			}
			
			for(var i : int = 0 ; i < advanData.length ; i++) {
				if(advanData[i][_listData.dataField] == true) {
					selectedIdx++;
				}
			}
			if(selectedIdx == 0) {
				selected = false;
				_headerFlag = false;
			}
		}
		
		override public function get data():Object
		{
			return _data;
		}
		
		/*
		override mx_internal function setSelected(value:Boolean):void
		{
			super.setSelected(value);
			if(listData != null && listData.rowIndex == 0){
		}
		*/
	  
	}
}

